<?php

class CS_Model_Engine_Mysql extends CS_Model_Engine
{

	public $connection;

	public $resource;

	public function connect()
	{
		
		$this->connection =  mysql_connect(CS_Config::read('Database.host'), CS_Config::read('Database.user'), CS_Config::read('Database.pass'));

		$this->selectDb();

		return $this->connection;
	}

	public function selectDb()
	{
		mysql_select_db(CS_Config::read('Database.db'));
	}
	
	public function showTables()
	{
		$this->query("SHOW TABLES");

		$tables = array();

		if(is_resource($this->resource))
		{
			$db = CS_Config::read('Database.db');
			while($table = $this->fetchRow())
			{
				$property = 'Tables_in_'.$db;
				$tables[] = $table->{$property};
			}
		}

		return $tables;
	}

	public function fetchRow()
	{
		return mysql_fetch_object($this->resource);
	}

	public function query($sql = null)
	{
		if(empty($sql))
		{
			return false;
		}

		try{

			 $this->resource = mysql_query($sql);

			 if(!$this->resource)
			 {
				throw new CS_Error_Exception(mysql_error());
			 } else {
				return $this->resource;
			 }

		} catch(CS_Error_Exception $e){
				$e->printError();
			}
	}
}
